//
//  ChatViewController.swift
//  HyphenateIMDemo
//
//  Created by Shang Hai Rui Xi on 2019/1/3.
//  Copyright © 2019 Shang Hai Rui Xi. All rights reserved.
//

import UIKit

class ChatViewController: ChatContentViewController {

    open var conversation: EMConversation
    
    fileprivate var currentUser: UserModel = UserModel.getMyInfo()
    fileprivate var maxTime = 0
    fileprivate var minTime = 0
    
    private var pageNum: Int = 0
    
    public required init(conversation: EMConversation) {
        self.conversation = conversation
        super.init(nibName: nil, bundle: nil)
    }

    public required init(aConversationId: String, aType: EMConversationType) {
        self.conversation = (EMClient.shared()?.chatManager.getConversation(aConversationId, type: aType, createIfNotExist: true)) ?? EMConversation.init()
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        EMClient.shared()?.chatManager.add(self, delegateQueue: nil)
        loadMessages(page: pageNum)
    }
    
    deinit {
        EMClient.shared()?.chatManager.remove(self)
    }
    
    override public func tapAvatarView(message: Messageable) {}
    
    override public func clickImageView(message: Messageable, image: UIImage?) { }
    
    override public func refreshChatContentView(chatView: ChatContentView) {
        pageNum += 1
        loadMessages(page: pageNum)
        chatContentView.stopRefresh()
    }
    
    override func keyboardOutPutAttribute(_ attribute: NSAttributedString) {
        send(forText: attribute)  //发送文本消息
    }
    
    override func functionView(view: FunctionsView, didSelectFunctionType type: FunctionType) {
        switch type {
        case .photo:
            let image = UIImage.init(named: "333.jpg")
            send(forImage: image)
        }
    }
}

//MARK: 加载会话内容列表
extension ChatViewController {
    private func loadMessages(page: Int) {
        var messageid = ""
        if messages.count > 0 {
            messageid = messages.first?.msgId ?? ""
        }
        conversation.loadMessagesStart(fromId: messageid, count: 10, searchDirection: EMMessageSearchDirectionUp) { [weak self] (aMessages, _) in
            guard let aMessages = aMessages, aMessages.count != 0 else { return }
            
            var msgs: [Message] = []
            aMessages.enumerated().forEach({ (index, aMsg) in
                guard let aMsg = aMsg as? EMMessage, let msg = self?.parseMessage(aMsg) else { return }
                self?.conversation.markMessageAsRead(withId: aMsg.messageId, error: nil)
                msgs.append(msg)
            })
            if page != 0 {
                self?.chatContentView.insert(contentsOf: msgs, at: 0)
            } else {
                self?.chatContentView.append(contentsOf: msgs)
                self?.chatContentView.scrollToLastMessage(animated: true)
            }
            self?.messages.insert(contentsOf: msgs, at: 0)
        }
    }
    
    //MARK: 将从环信加载出的会话列表全部自定义化
    private func parseMessage(_ message: EMMessage) -> Message {
        return message.parseMessage(updateMediaMessage: { [weak self](aMsg, data) in
            self?.updateMediaMessage(aMsg, data: data)
        })
    }
    
    //MARK: 将Media数据加载出来后UI赋值
    private func updateMediaMessage(_ message: EMMessage, data: Data) {
        DispatchQueue.main.async {
            if let index = self.messages.indexs(at: message) {
                let msg = self.messages[index]
                
                switch message.body.type {
                case EMMessageBodyTypeImage:
                    let imageContent = msg.content as! MessageImageContent
                    let image = UIImage.init(data: data)
                    imageContent.imageSize = image?.size
                    imageContent.image = image
                    msg.content = imageContent
                    msg.updateSizeIfNeeded = true
                default:
                    break;
                }
                self.chatContentView.update(msg, at: index)
            }
        }
    }
}

//MARK: EMChatManagerDelegate
extension ChatViewController: EMChatManagerDelegate {
    func messagesDidReceive(_ aMessages: [Any]!) {
        var msgs: [Message] = []
        aMessages.forEach { (aMsg) in
            guard let aMsg = aMsg as? EMMessage else { return }
            if conversation.conversationId == aMsg.conversationId {
                conversation.markMessageAsRead(withId: aMsg.messageId, error: nil)
                let msg = self.parseMessage(aMsg)
                msgs.append(msg)
            }
        }
        self.chatContentView.insert(contentsOf: msgs, at: self.messages.count)
        self.messages.append(contentsOf: msgs)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) {
            self.chatContentView.scrollToLastMessage(animated: false)
        }
    }
}

// 处理消息--> 转化为自定义消息类型
extension ChatViewController {
    //MARK: 发送消息（进行组合后发送）
    public func send(_ message: Message, _ EMmessage: EMMessage?) {
        guard let emessage = EMmessage else { return }
//        if isNeedInsertTimeLine(Int(emessage.localTime)) {
//            message.options.isShowTime = true
//        }
        message.msgId = emessage.messageId
        message.name = currentUser.nickname
        message.sender = currentUser
        message.time = Date()
        message.senderAvator = currentUser.avatarImage
        message.options.alignment = .right
        message.options.state = .sending
        if conversation.type == EMConversationTypeChat {
            message.targetType = .single
        } else {
            message.targetType = .group
        }
        chatContentView.append(message)
        messages.append(message)
        chatContentView.scrollToLastMessage(animated: false)
        
        // - 上传环信服务器消息  ---->>>
        EMClient.shared()?.chatManager.send(EMmessage, progress: nil, completion: nil)
    }
    
    //MARK: 发送文本消息
    public func send(forText text: NSAttributedString) {
        let message = Message.init(content: MessageTextContent.init(text: text))
        let content = EMTextMessageBody.init(text: text.string)
        
        let EMmessage = EMMessage.init(conversationID: conversation.conversationId, from: currentUser.userid, to: conversation.conversationId, body: content, ext: [:])
        send(message, EMmessage)
    }
    
    //MARK: 发送图片
    public func send(forImage image: UIImage?) {
        guard let image = image else { return }
        let message = Message.init(content: MessageImageContent.init(image: image))
        let imageData = image.jpegData(compressionQuality: 1)
        let thumbnailData = image.jpegData(compressionQuality: 0.5)
        let content = EMImageMessageBody.init(data: imageData, thumbnailData: thumbnailData)
        
        let EMmessage = EMMessage.init(conversationID: conversation.conversationId, from: currentUser.userid, to: conversation.conversationId, body: content, ext: [:])
        send(message, EMmessage)
    }
}

// 私有方法
extension ChatViewController {
    //MARK: 是否需要插入时间
    private func isNeedInsertTimeLine(_ time: Int) -> Bool {
        if maxTime == 0 || minTime == 0 {
            maxTime = time
            minTime = time
            return true
        }
        if (time - maxTime) >= 5 * 60000 {
            maxTime = time
            return true
        }
        if (minTime - time) >= 5 * 60000 {
            minTime = time
            return true
        }
        return false
    }
}
